package com.naizhuai.ui.ainote.notesetting;

import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;

import com.naizhuai.Model.db.ainote.Note;
import com.naizhuai.Model.db.ainote.NoteDataSourse;
import com.naizhuai.Model.db.ainote.NoteRepository;
import com.naizhuai.util.TimeUtils;

import java.util.Date;

/**
 * @author：lichenxi
 * @date 2018/2/26 23
 * email：525603977@qq.com
 * Fighting
 */
public class AddDetialPresenter implements AddDetialContract.Presenter {
    private AddDetialContract.View mAddDetialView;
    private NoteRepository mRepository;
    private Note tempNote;
    public AddDetialPresenter(int noteId,NoteRepository repository) {
        mRepository = repository;
        mNoteId = noteId;
    }

    @Nullable
    private int mNoteId;

    @Override
    public void takeView(AddDetialContract.View view) {
        this.mAddDetialView=view;
        if (!isNewNote()){
            mAddDetialView.showTimeStamp();
            populateTask();
        }
    }

    @Override
    public void dropView() {
       this.mAddDetialView=null;
    }

    @Override
    public void saveTask(String title, String description) {
         if (isNewNote()){
             createNote(title,description);
         }else {
             updateNote(title,description);
         }
    }

    private void updateNote(String title, String description) {
        Note note=new Note(title,description);
        note.setNoteid(mNoteId);
        note.setCreation(tempNote.creation);
        mRepository.updateNote(note);
        if (mAddDetialView!=null){
            mAddDetialView.showTasksList();
        }
    }

    private void createNote(String title, String description) {
        Note note=new Note(title,description);
        if (note.isEmpty()){
            mAddDetialView.showEmptyNoteError();
        }else {
            mRepository.saveNote(note);
            if (mAddDetialView!=null){
                mAddDetialView.showTasksList();
            }

        }


    }

    @Override
    public void populateTask() {
        mRepository.getNote(mNoteId, new NoteDataSourse.GetNoteCallback() {
            @Override
            public void onNoteLoaded(Note note) {
                   tempNote=note;
                  if (mAddDetialView!=null){
                      mAddDetialView.setTitle(note.title);
                      mAddDetialView.setDescription(note.content);
                      mAddDetialView.setCreation("创建于:"+TimeUtils.date2String(note.creation));
                      mAddDetialView.setLastupdate("更新于:"+TimeUtils.date2String(note.last_update));
                  }
            }

            @Override
            public void onDataNotAvailable() {
                mAddDetialView.showEmptyNoteError();
            }
        });

    }
    private boolean isNewNote() {
        return mNoteId ==-1;
    }
}
